﻿using System;
using System.Data;
using System.IO;
using System.Xml;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class Subscribe : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string subType = Request["subtype"];
            if ("sub".Equals(subType))
            {
                string subEmail = Request["sbemail"];

                var loggerEmail = new LoggerEmail
                                              {
                                                  Email = subEmail,
                                                  Type = EmailType.Subcribe
                                              };

                var result = new XmlDocument();
                result.LoadXml("<ResultData><resultCode /><resultDesc /></ResultData>");
                try
                {
                    LoggerEmailServices.SaveOrUpdate(loggerEmail);

                    SendConfirmSubcribeEmail(loggerEmail);
                    // ReSharper disable PossibleNullReferenceException
                    result.DocumentElement.SelectSingleNode("resultCode").InnerText = "SUCCESS";
                    // ReSharper restore PossibleNullReferenceException
                }
                catch (ObjectAlreadyExistException)
                {
                    // ReSharper disable PossibleNullReferenceException
                    result.DocumentElement.SelectSingleNode("resultCode").InnerText = "ERROR";
                    result.DocumentElement.SelectSingleNode("resultDesc").InnerText = "E-mail của bạn đã lưu trử trong dử liệu của chúng tôi.";
                    // ReSharper restore PossibleNullReferenceException))
                }

                Response.ContentType = "text/xml";
                Response.Write(result.OuterXml);
                Response.End();
            }

            if ("unsub".Equals(subType)) return;

            var unsbId = Request["unsbid"];
            var itemId = new Guid(unsbId);

            LoggerEmailServices.Delete(itemId);
        }

        #region Private Methods
        private void SendConfirmSubcribeEmail(LoggerEmail loggerEmail)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["ConfirmSubcribe"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            var confirmSubcribeUrl = string.Format("{0}/confirmsubscribe.aspx?itid={1}", SiteUrl, loggerEmail.ID);
            var unSubcribeUrl = string.Format("{0}/Subscribe.aspx?subtype=unsub&unsbid={1}", SiteUrl, loggerEmail.ID);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.ConfirmSubcribeEmailBuilder(Convert.ToString(rows[0]["Content"]), loggerEmail.Email, confirmSubcribeUrl, unSubcribeUrl);

            EmailSender.SendMail(subject, contentMail, loggerEmail.Email);
        }
        #endregion
    }
}
